package com.portal.backend.controller;

import com.portal.backend.payload.CommentRequest;
import com.portal.backend.payload.CommentResponse;
import com.portal.backend.service.CommentService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CommentController {

    @Autowired
    private CommentService commentService;

    // 创建评论
    @PostMapping("/articles/{articleId}/comments")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<CommentResponse> createComment(@PathVariable Long articleId, 
                                                       @Valid @RequestBody CommentRequest commentRequest) {
        CommentResponse commentResponse = commentService.createComment(articleId, commentRequest);
        return new ResponseEntity<>(commentResponse, HttpStatus.CREATED);
    }

    // 获取文章下的所有评论 (分页)
    @GetMapping("/articles/{articleId}/comments")
    public IPage<CommentResponse> getCommentsByArticle(@PathVariable Long articleId,
                                                      @RequestParam(defaultValue = "1") long current,
                                                      @RequestParam(defaultValue = "10") long size) {
        return commentService.getCommentsByArticleId(articleId, current, size);
    }

    // 获取单条评论 (可选, 根据需要)
    @GetMapping("/comments/{commentId}")
    public ResponseEntity<CommentResponse> getCommentById(@PathVariable Long commentId) {
        CommentResponse commentResponse = commentService.getCommentById(commentId);
        return ResponseEntity.ok(commentResponse);
    }

    // 更新评论
    @PutMapping("/comments/{commentId}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<CommentResponse> updateComment(@PathVariable Long commentId, 
                                                       @Valid @RequestBody CommentRequest commentRequest) {
        CommentResponse commentResponse = commentService.updateComment(commentId, commentRequest);
        return ResponseEntity.ok(commentResponse);
    }

    // 删除评论
    @DeleteMapping("/comments/{commentId}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> deleteComment(@PathVariable Long commentId) {
        commentService.deleteComment(commentId);
        return ResponseEntity.ok("Comment deleted successfully");
    }
} 